有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java添加鼠标侦听器以删除目标

DefaultTableModel modeltable = new DefaultTableModel(8,8);

table = new JTable(modeltable);
table.setBorder(BorderFactory.createLineBorder (Color.blue, 2));

int height = table.getRowHeight();
table.setRowHeight(height=50);

table.setColumnSelectionAllowed(true);
table.setDragEnabled(true);

le1.setFillsViewportHeight(true);

panel.add(table);
panel.setSize(400,400);

    DnDListener dndListener = new DnDListener();
    DragSource dragSource = new DragSource();
    DropTarget dropTarget1 = new DropTarget(table, dndListener);

   DragGestureRecognizer dragRecognizer2 = dragSource.
            createDefaultDragGestureRecognizer(option1, 
          DnDConstants.ACTION_COPY, dndListener);
   DragGestureRecognizer dragRecognizer3 = dragSource.
            createDefaultDragGestureRecognizer(option2, 
            DnDConstants.ACTION_COPY, dndListener);


}
}

我在将鼠标侦听器添加到作为拖放目标的“表”中时遇到了一个问题,即无论拖放组件从鼠标中拖放到哪里,都要接受拖放组件。在这段代码中,当组件下降到下降目标时,它总是会进入默认位置。我无法自定义放置目标的位置。请有人帮我做这个。 提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    那些听众的水平太低了。实现dnd的适当方法是实现自定义TransferHandler,并将该自定义处理程序设置到表中

     public class MyTransferHandler extends TransferHandler {
    
        public boolean canImport(TransferHandler.TransferSupport info) {
            // we only import Strings
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                return false;
            }
    
            JTable.DropLocation dl = (JTable.DropLocation)info.getDropLocation();
            // ... your code to decide whether the data can be dropped based on location 
        }
    
        public boolean importData(TransferHandler.TransferSupport info) {
            if (!info.isDrop()) {
                return false;
            }
    
            // Check for String flavor
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                displayDropLocation("Table doesn't accept a drop of this type.");
                return false;
            }
    
            JTable.DropLocation dl = (JTable.DropLocation)info.getDropLocation();
            // ... your code to handle the drop
       }
    
    }
    
    // usage
    myTable.setTransferHandler(new MyTransferHandler());
    

    有关详细信息,请参见Swing标记描述中链接到的在线教程中的示例,即chapter Drag and Drop,上面的代码片段是c&;从基本示例中删除